package com.smit.livevideo.sample.controller;

import android.content.ContentValues;
import android.os.SystemClock;

import com.smit.dvb.DVBServiceInfo;
import com.smit.dvb.DVBTunerInfo;
import com.smit.livevideo.sample.CommonData;
import com.smit.livevideo.sample.dao.ChannelDAO;
import com.smit.livevideo.sample.db.SqliteBaseUtil;
import com.smit.livevideo.sample.db.Tables;
import com.smit.livevideo.sample.util.SDKAPIUtil;
import com.smit.livevideo.sample.util.ShareValueUtil;
import com.smit.utils.LogUtil;
import com.smit.utils.StrUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by smfang on 2015/11/24.
 * 搜台控制器
 */
public final class ScanServicesController {
    /**
     * 自动搜台标志
     */
    public static final int SCAN_AUTO = 0;
    /**
     * 全频点搜台标志
     */
    public static final int SCAN_FULL = 1;
    /**
     * 手动搜台标志
     */
    public static final int SCAN_MANUAL = 2;
    private static final String TAG = ScanServicesController.class.getSimpleName();

    private static int searchType = SCAN_FULL;
    private static DVBTunerInfo dvbTunerInfo = null;

    private static boolean bDVBScaning = false;
    private static int scanStatus = -1;
    private static String firstSearchedChannelName;
    private static int totalChannelCount = 0;

    private ScanServicesController() {

    }

    public static boolean isFromChannelSettings() {
        return false;
    }

    public static int getSearchType() {
        return searchType;
    }

    public static void setSearchType(int type) {
        searchType = type;
    }

    public static void setSingleSearchParam(DVBTunerInfo dvbTunerInfo) {
        ScanServicesController.dvbTunerInfo = dvbTunerInfo;
    }

    public static boolean isDVBScaning() {
        return bDVBScaning;
    }

    public static void setDVBScaningStatus(boolean dvbScan) {
        bDVBScaning = dvbScan;
    }

    public static int getScanStatus() {
        return scanStatus;
    }

    /**
     * 设置搜台标志位
     *
     * @param status 需要设置的搜台状态位
     */
    public static void setScanStatus(int status) {
        scanStatus = status;
    }

    /**
     * 启动搜台
     */
    public static void startSearch() {
        firstSearchedChannelName = null;
        scanStatus = -1;
        totalChannelCount = 0;

        if (searchType == SCAN_MANUAL && dvbTunerInfo != null) {
            SDKAPIUtil.getScanControl().manualScan(dvbTunerInfo);
        } else if (searchType == SCAN_FULL) {
            SDKAPIUtil.getScanControl().fullScan(115000, 858000);
        } else if (searchType == SCAN_AUTO) {
            SDKAPIUtil.getScanControl().autoScan(115000, 858000);
        }
    }

    /**
     * 搜索到节目个数的回调
     * @param dvbServiceInfo 搜到的dvb节目信息
     * @return int
     */
    public static int onScanServicesFound(final DVBServiceInfo[] dvbServiceInfo) {
        LogUtil.debug(TAG, "onScanServicesFound~~~~~");
        int num = 0;
        if (dvbServiceInfo != null) {
            LogUtil.debug(TAG, "programs len = " + dvbServiceInfo.length);
            for (int i = 0; i < dvbServiceInfo.length; i++) {
                int type = dvbServiceInfo[i].serviceType;
                LogUtil.trace(TAG,
                        "dvbServiceInfo serviceType:" + type + " serviceName:" + dvbServiceInfo[i].serviceName);
                if (type == dvbServiceInfo[i].DVB_GROUP_TV) {
                    num++;
                    if (StrUtil.isNullOrEmpty(firstSearchedChannelName)) {
                        firstSearchedChannelName = dvbServiceInfo[i].serviceName;
                    }
                }
                final String name = dvbServiceInfo[i].serviceName;
                LogUtil.debug(TAG, name);
            }
            totalChannelCount += num;
        }
        return totalChannelCount;
    }

    /**
     * 这里保存最后一个需要播放的频道索引，现在的思路是保存最后需要播放频道， 然后进入直播后直接调用播放最后一个频道,
     * 不需要在这里调用DVBAdapter的ServicePlayByIndex来进行播放 ， 播放的工作转移到activity
     */
    public static void setLastPlayChannel() {
        LogUtil.error(TAG, "setLastPlayChannel start firstSearchedChannelName:" + firstSearchedChannelName);
        List<String> channelNameList = ChannelDAO.getInstance().getCurrentChannelNameList();
        List<Integer> channelIndexList = ChannelDAO.getInstance().getCurrentChannelIndexList();

        if (ScanServicesController.getSearchType() == ScanServicesController.SCAN_MANUAL) {
            if (channelNameList != null) {
                int i = channelNameList.indexOf(firstSearchedChannelName);
                if (StrUtil.isNullOrEmpty(firstSearchedChannelName) == false && i >= 0 && i < channelIndexList.size()) {
                    ShareValueUtil.putShareIntValue(CommonData.PREF_LAST_PLAY_CHANNEL_INDEX, channelIndexList.get(i));
                    ShareValueUtil.putShareIntValue(CommonData.PREF_LAST_PLAY_CHANNEL_INDEX_BAK,
                            channelIndexList.get(i));
                }
            }
        } else {
            if (channelIndexList != null && channelIndexList.size() > 0) {
                ShareValueUtil.putShareIntValue(CommonData.PREF_LAST_PLAY_CHANNEL_INDEX, channelIndexList.get(0));
                ShareValueUtil.putShareIntValue(CommonData.PREF_LAST_PLAY_CHANNEL_INDEX_BAK, channelIndexList.get(0));
            }
        }

        firstSearchedChannelName = null;
        LogUtil.error(TAG, "setLastPlayChannel end<<<");
    }

    /**
     * 保存搜索到的频点、频道名称等参数到数据库
     */
    public static void saveServicesInfoToDB() {
        SDKAPIUtil.getSetupControl().setServiceGroupId(DVBServiceInfo.DVB_GROUP_TV);
        DVBServiceInfo[] dvbServiceInfos = SDKAPIUtil.getServiceControl().getAllServices();
        SqliteBaseUtil.getInstace().deleteAll(Tables.DVBChannel.DVB_CHANNEL_TABLE_NAME);

        if (dvbServiceInfos == null || dvbServiceInfos.length == 0) {
            LogUtil.error(TAG, "saveChannelInfoToDB serviceDatas is null or no data");
            return;
        }

        List<ContentValues> listAll = new ArrayList<ContentValues>();
        //先保存全频道列表
        LogUtil.debug(TAG, "saveChannelInfoToDB time01=" + SystemClock.uptimeMillis());
        LogUtil.trace(TAG, "dvbServiceInfos.length:" + dvbServiceInfos.length);
        for (int i = 0; i < dvbServiceInfos.length; i++) {
            ContentValues contentValues = new ContentValues();
            contentValues.put(Tables.DVBChannel.DVB_CHANNEL_FIELD_CHANNELNAME,
                    new String(dvbServiceInfos[i].serviceName.trim()));
            contentValues.put(Tables.DVBChannel.DVB_CHANNEL_FIELD_CHANNELNUMBER, dvbServiceInfos[i].channelNumber);
            contentValues.put(Tables.DVBChannel.DVB_CHANNEL_FIELD_FREQ, dvbServiceInfos[i].frequency + "");
            contentValues.put(Tables.DVBChannel.DVB_CHANNEL_FIELD_SYM, dvbServiceInfos[i].symbolRate + "");
            contentValues.put(Tables.DVBChannel.DVB_CHANNEL_FIELD_MOD, dvbServiceInfos[i].modulation + "");
            contentValues.put(Tables.DVBChannel.DVB_CHANNEL_FIELD_INDEX, i + "");
            listAll.add(contentValues);
        }
        LogUtil.debug(TAG, "saveChannelInfoToDB time02=" + SystemClock.uptimeMillis());
        ChannelDAO.getInstance().initAllChannelList(listAll);
        LogUtil.debug(TAG, "saveChannelInfoToDB time03=" + SystemClock.uptimeMillis());
    }
}
